/*
 * SkyBoxContainer.java
 * 
 * Created on 2008-04-17, 18:26:29
 */

package planesimulator.utils;

import java.util.HashMap;
import java.util.Map;

import java.net.URL;

import com.jme.scene.Skybox;
import com.jme.system.JmeException;
import com.jme.util.TextureManager;
import com.jme.image.Texture;

/**
 * Skybox container (contains skyboxes by name)
 * 
 * @author Mateusz 'm4linka' Malinowski (m4linka@gmail.com)
 */
public class SkyBoxContainer {

  /** The skybox object */
  protected transient Map<String, Skybox> skyboxes;
  
  /** 
   * the x-size, y-size and z-size of the skybox 
   * in both directions from the center 
   */
  protected final transient float x_extent, y_extent, z_extent;
  
  
  /**
   * Constructor
   * 
   * @param x_extent the x-size of the skybox in both directions from the center
   * @param y_extent the y-size of the skybox in both directions from the center
   * @param z_extent the z-size of the skybox in both directions from the center
   */
  public SkyBoxContainer(final float x_extent, 
      final float y_extent, final float z_extent) {
    this.x_extent = x_extent;
    this.y_extent = y_extent;
    this.z_extent = z_extent;
    skyboxes = new HashMap<String, Skybox>();
  }

  
  /**
   * Add new skybox 
   * 
   * @param name skybox's name
   * @param textures_path 6-sized array of textures' pathfiles in the following
   *        order: north, south, east, west, top, down 
   */
  public void addSkybox(final String name, final URL textures_path[]) {
    
    if(textures_path.length != 6) {
      throw new JmeException(
          "Length of textures pathfile array must contain exactly 6 elements.");
    }
    
    if(skyboxes.containsKey(name)) {
      throw new JmeException("Skybox's names must be uniqe.");
    }
    
    final Skybox skybox = new Skybox(name, x_extent, y_extent, z_extent);
    
    Texture[] textures = new Texture[6];
    for(int i = 0; i < textures.length; i++) {
      textures[i] = TextureManager.loadTexture(
          textures_path[i], Texture.MM_LINEAR, Texture.FM_LINEAR);
    }
    
    skybox.setTexture(Skybox.NORTH, textures[Skybox.NORTH]);
    skybox.setTexture(Skybox.SOUTH, textures[Skybox.SOUTH]);
    skybox.setTexture(Skybox.EAST, textures[Skybox.EAST]);
    skybox.setTexture(Skybox.WEST, textures[Skybox.WEST]);
    skybox.setTexture(Skybox.UP, textures[Skybox.UP]);
    skybox.setTexture(Skybox.DOWN, textures[Skybox.DOWN]);
    skybox.preloadTextures();
    
    // for efficiency, if something doesn't work comment it 
    skybox.lockBounds();
    skybox.lockMeshes();
    
    skyboxes.put(name, skybox);
  }
  
  
  /**
   * Get skybox from container by name
   * 
   * @param name skybox's name (its identifier)
   */
   public Skybox getSkybox(final String name) {
     return skyboxes.get(name);
   }
}
